package ds.adt;

import java.util.Iterator;

/**
 * Implements Stack data structure.
 *
 * @author shankar
 *
 * @param <Item>
 */
public class Stack<Item> implements Iterable<Item> {

	private Node top;
	private int size;

	public Stack() {
		size = 0;
	}

	private class Node {
		Item data;
		Node next;
	}

	public void push(Item item) {
		++size;
		Node current = top;
		top = new Node();
		top.data = item;
		top.next = current;
	}

	public Item pop() {
		--size;
		Item item = top.data;
		top = top.next;
		return item;
	}

	public boolean isEmpty() {
		return (top == null);
	}

	public int size() {
		return size;
	}

	@Override
	public Iterator<Item> iterator() {
		return new ListIterator();
	}

	private class ListIterator implements Iterator<Item> {

		private Node current = top;

		@Override
		public boolean hasNext() {
			return (current != null);
		}

		@Override
		public Item next() {
			Item item = current.data;
			current = current.next;
			return item;
		}

		@Override
		public void remove() {
		}
	}

}
